package net.entelijan.cobean.table;

import java.io.Serializable;
import java.util.Comparator;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanWrapper;

@SuppressWarnings("unchecked")
class PropertiesSorter implements Comparator<BeanWrapper>, Serializable {

	private static final long serialVersionUID = 1L;

	private static Log log = LogFactory.getLog(PropertiesSorter.class);

	private String propertyName;
	private boolean descending;

	public PropertiesSorter(String propertyName, boolean descending) {
		this.propertyName = propertyName;
		this.descending = descending;
	}

	public int compare(BeanWrapper bw1, BeanWrapper bw2) {
		int re = 0;
		try {
			Object val1 = bw1.getPropertyValue(this.propertyName);
			Object val2 = bw2.getPropertyValue(this.propertyName);
			if (descending) {
				re = ((Comparable) val1).compareTo(val2);
			} else {
				re = ((Comparable) val2).compareTo(val1);
			}
		} catch (Exception e) {
			log.warn("Could not compare property '" + propertyName + "' of "
					+ bw1 + " and " + bw2 + " because: " + e.getMessage());
		}
		return re;
	}

}
